package com.huak.zookeeper.connection;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.ACL;

import java.util.ArrayList;

/**
 * @author liuhuan
 * @date 2018/9/16 09:10
 * @description
 */
@Slf4j
@Data
public class ZkNodeOperator implements Watcher {
    public static final String SERVER_PATH="192.168.0.128:2181";
    public static final int TIMEOUT=5000;

    private ZooKeeper zooKeeper=null;

    public ZkNodeOperator() {

    }

    public ZkNodeOperator(String connectionString)  {
        try {
            zooKeeper=new ZooKeeper(connectionString,TIMEOUT,new ZkNodeOperator());
        }catch (Exception e) {
            log.error(e.getMessage(),e);
            if(zooKeeper!=null){
                try {
                    zooKeeper.close();
                } catch (InterruptedException e1) {
                    log.error(e1.getMessage(),e1);
                }
            }
        }
    }

    @Override
    public void process(WatchedEvent watchedEvent) {

    }

    /**
     * 创建节点
     * @param path
     * @param data
     * @param acls
     */
    public void createNode(String path, byte[] data, ArrayList<ACL> acls) {
        String result="";
        try{
            /**同步或者异步创建节点，都不支持子节点的递归创建，异步有一个callback函数
             * 参数：
             *path：创建的路径
             *data：存储数据的bytes
             *acls：控制权限策略
             *       Ids.open_acl_unsafe-->world：anyone：cdrwa
             *       CREATOR_ALL_ACL-->auth:user:password:cdrwa
             *createMode:节点类型，是个枚举
             *        PERSISTENT：持久节点
             *        PERSISTENT_SEQUENTIAL :持久顺序节点
             *        EPHEMERAL:临时节点
             *        EPHEMERAL_SEQUENTIAL:临时顺序节点
             */
            //同步方式
            //result=zooKeeper.create(path,data,acls, CreateMode.EPHEMERAL);
            String ctx="{'create':'success'}";
            zooKeeper.create(path,data,acls,CreateMode.PERSISTENT,new CreateCallBack(),ctx);
            log.info("创建节点:{}成功",result);
            Thread.sleep(2000);
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
    }

    public static void main(String[] args) throws Exception{
        ZkNodeOperator zkNodeOperator=new ZkNodeOperator(SERVER_PATH);
        //zkNodeOperator.createNode("/testNode","testNode".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE);
        //同步修改
//        Stat stat=zkNodeOperator.getZooKeeper().setData("/testNode","xyz".getBytes(),0);
        //异步修改
        zkNodeOperator.getZooKeeper().setData("/testNode","xyz".getBytes(),1,new UpdateCallBack(),"1");
        Thread.sleep(2000);
        //log.info("当前版本：{}",stat.getVersion());
        zkNodeOperator.getZooKeeper().getChildren("/imooc",true);
    }


}
